package com.example.hello.service.impl;

import com.example.hello.dto.CommentDTO;
import com.example.hello.entity.Attraction;
import com.example.hello.entity.Comment;
import com.example.hello.mapper.AttractionMapper;
import com.example.hello.mapper.CommentMapper;
import com.example.hello.service.CommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private AttractionMapper attractionMapper;

    @Override
    @Transactional
    public Comment addComment(CommentDTO commentDTO, Long userId) {
        // 检查景点是否存在
        Attraction attraction = attractionMapper.getAttractionById(commentDTO.getAttractionId());
        if (attraction == null) {
            throw new RuntimeException("景点不存在");
        }
        
        // 如果是回复，检查父级留言是否存在
        if (commentDTO.getParentCommentId() != null && commentDTO.getParentCommentId() > 0) {
            Comment parentComment = commentMapper.getCommentById(commentDTO.getParentCommentId());
            if (parentComment == null) {
                throw new RuntimeException("要回复的留言不存在");
            }
            
            // 确保父级留言属于同一景点
            if (!parentComment.getAttractionId().equals(commentDTO.getAttractionId())) {
                throw new RuntimeException("回复的留言与当前景点不匹配");
            }
        } else {
            commentDTO.setParentCommentId(0L);
        }
        
        // 创建新留言
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDTO, comment);
        comment.setUserId(userId);
        comment.setLikeCount(0);
        comment.setStatus(0);  // 0-待审核 1-正常 2-屏蔽
        comment.setIsTop(false);
        
        // 保存留言
        commentMapper.insertComment(comment);
        
        // 返回保存后的留言，包含用户和景点信息
        return commentMapper.getCommentById(comment.getCommentId());
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId) {
        // 验证评论是否存在且属于当前用户
        int count = commentMapper.countUserComment(commentId, userId);
        if (count == 0) {
            throw new RuntimeException("评论不存在或无权删除");
        }
        
        // 删除子评论
        commentMapper.deleteChildComments(commentId);
        
        // 删除评论
        return commentMapper.deleteCommentById(commentId) > 0;
    }

    @Override
    @Transactional
    public boolean adminDeleteComment(Long commentId) {
        // 删除子评论
        commentMapper.deleteChildComments(commentId);
        
        // 删除评论
        return commentMapper.deleteCommentById(commentId) > 0;
    }

    @Override
    public Comment getCommentById(Long commentId) {
        return commentMapper.getCommentById(commentId);
    }

    @Override
    public PageInfo<Comment> getCommentsByAttractionId(Long attractionId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> comments = commentMapper.getCommentsByAttractionId(attractionId, 1); // 状态为1表示正常
        return new PageInfo<>(comments);
    }

    @Override
    public PageInfo<Comment> getCommentsByUserId(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> comments = commentMapper.getCommentsByUserId(userId);
        return new PageInfo<>(comments);
    }

    @Override
    @Transactional
    public boolean updateCommentStatus(Long commentId, Integer status) {
        Comment comment = new Comment();
        comment.setCommentId(commentId);
        comment.setStatus(status);
        return commentMapper.updateComment(comment) > 0;
    }

    @Override
    @Transactional
    public boolean setCommentTop(Long commentId, Boolean isTop) {
        return commentMapper.updateTopStatus(commentId, isTop) > 0;
    }

    @Override
    public List<Comment> getTopComments(Long attractionId) {
        return commentMapper.getTopComments(attractionId);
    }

    @Override
    @Transactional
    public boolean likeComment(Long commentId) {
        return commentMapper.updateLikeCount(commentId, 1) > 0;
    }

    @Override
    public PageInfo<Comment> getAllComments(Integer pageNum, Integer pageSize, String orderBy, String orderDirection, Integer status) {
        // 验证排序字段，防止SQL注入
        String validOrderBy = validateOrderBy(orderBy);
        // 验证排序方向
        String validDirection = "asc".equalsIgnoreCase(orderDirection) ? "asc" : "desc";
        
        // 构建排序字符串
        String orderClause = validOrderBy + " " + validDirection;
        
        System.out.println("开始分页查询: 页码=" + pageNum + ", 每页记录数=" + pageSize + ", 排序=" + orderClause);
        
        // 使用PageHelper的startPage方法，同时设置排序
        PageHelper.startPage(pageNum, pageSize, orderClause);
        
        // 执行查询，传入状态参数
        List<Comment> comments = commentMapper.getAllCommentsWithStatus(status);
        
        PageInfo<Comment> pageInfo = new PageInfo<>(comments);
        System.out.println("分页查询结果: 总记录数=" + pageInfo.getTotal() + ", 总页数=" + pageInfo.getPages());
        
        // 返回分页结果
        return pageInfo;
    }

    /**
     * 验证排序字段，防止SQL注入
     */
    private String validateOrderBy(String orderBy) {
        // 允许的排序字段列表
        List<String> allowedFields = List.of("created_at", "like_count", "rating");
        
        // 将驼峰命名转换为下划线命名
        String fieldName = camelToUnderscore(orderBy);
        
        // 检查是否是允许的排序字段
        if (allowedFields.contains(fieldName)) {
            return "c." + fieldName;
        }
        
        // 默认按创建时间排序
        return "c.created_at";
    }

    /**
     * 将驼峰命名转换为下划线命名
     */
    private String camelToUnderscore(String camel) {
        return camel.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
    }
} 